import 'package:flutter/material.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
import 'package:sleep/help_style.dart';
import 'dart:ui' as ui;

import 'package:sleep/provider/sleep_osash_state_provider.dart';

class SleepStateWidget extends ConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    final osash = ref.watch(sleepOsashProvider);
    return Container(
      padding: const EdgeInsets.all(8),
      decoration: HelpStyle.decoration,
      child: CustomPaint(
        painter: ValuePinter((osash?.index.toDouble() != null
            ? (osash!.index.toDouble() + 1)
            : 0)),
        size: const Size(double.infinity, 30),
      ),
    );
  }
}

const valueCount = 4;
List<List<Color>> colors = const [
  [Color.fromARGB(255, 102, 187, 106), Color.fromARGB(255, 151, 187, 101)],
  [Color.fromARGB(255, 66, 165, 245), Color.fromARGB(255, 66, 165, 245)],
  [Color.fromARGB(255, 255, 158, 88), Color.fromARGB(255, 255, 158, 88)],
  [Color.fromARGB(255, 239, 83, 80), Color.fromARGB(255, 239, 83, 80)],
];

List<String> textes = ['Normal', 'Mild', 'Moderate', 'Severe'];

class ValuePinter extends CustomPainter {
  final double vaule; //  0 - 10

  ValuePinter(this.vaule);
  @override
  void paint(Canvas canvas, Size size) {
    double startX = 0;
    final margin = size.width / (valueCount * 4 + valueCount - 1);
    final width = margin * 4;
    int index = 0;

    while (startX < size.width) {
      final isOver = index >= vaule;
      final overColors = [HelpStyle.backgroundColor, HelpStyle.backgroundColor];
      final showColors = isOver ? overColors : colors[index];

      final Paint p = Paint()
        ..shader = ui.Gradient.linear(
          Offset(startX, 0),
          Offset(startX + width, 0),
          showColors,
          [0.0, 1.0],
        );

      canvas.drawRect(Rect.fromLTRB(startX, 0, startX + width, size.height), p);
      drawText(
          canvas, Size(width, size.height), Offset(startX, 0), textes[index]);
      startX += width + margin;
      index += 1;
    }
  }

  drawText(Canvas canvas, Size size, Offset offset, String text) {
    const textStyle = TextStyle(
      color: Colors.white,
      fontSize: 14.0,
    );

    final textSpan = TextSpan(
      text: text,
      style: textStyle,
    );

    final textPainter = TextPainter(
      text: textSpan,
      textDirection: TextDirection.ltr,
      textAlign: TextAlign.center,
    );

    textPainter.layout(minWidth: 0, maxWidth: size.width);

    textPainter.paint(
        canvas,
        Offset(offset.dx + (size.width - textPainter.width) * 0.5,
            offset.dy + (size.height - textPainter.height) * 0.5));
  }

  @override
  bool shouldRepaint(covariant ValuePinter oldDelegate) {
    return oldDelegate.vaule != vaule;
  }
}
